<template>
  <div >
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <div v-loading="loading"
          class="bg-page-header"
           style="display:flex;justify-content:space-between;background:#fff;"
          >
        <div style="width:100%;">
          <el-menu :default-active="activeIndex"
                   mode="horizontal"
                   active-text-color="#17B3A3"
                   @select="selectHander"
                   style="display: flex;justify-content:flex-end;">

            <li class="menu-item-header"
              
                style="margin-right:auto;margin-left:20px;display: flex; align-items: center;flex-direction: row;">
              <template v-if="isBotDetailPage&&!gadgetSetting.nextTiketPage">
                <el-image style="width: 20px; height: 20px;margin-right: 10px;display: flex;"
                          :src="$ossLink+'/app/bot/bot-icon-normal.png'"
                          fit="fill"></el-image>
                <el-tooltip :open-delay="1000"
                            :content="botDetailInfo.botName">
                  <span class="more_text_app2">{{  $route.query.name ?$route.query.name:  botDetailInfo.botName}}</span>
                </el-tooltip>
                <div>
                  <view-linked-info :linkKey="'Bot-detail-'+botDetailInfo.botId"></view-linked-info>
                </div>
              </template>
              <template v-else-if='!isBotDetailPage&&gadgetSetting.nextTiketPage'>
                <el-image style="width: 20px; height: 20px;margin-right: 10px;display: flex;"
                          :src="gadgetSetting.haderImg"
                          fit="fill"></el-image>
                <span>{{reportName?reportName:gadgetSetting.headerTitle}}</span>
                <div>
                  <view-linked-info :linkKey="'Report-detail-'+$getQuery('pageid')"></view-linked-info>
                </div>
              </template>
              <template v-else>
                <el-image style="width: 20px; height: 20px;margin-right: 10px;display: flex;"
                          :src="$ossLink+'/app/reportlayout/grid.png'"
                          fit="fill"></el-image>
                <span>{{reportName?reportName:gadgetSetting.headerTitle}}</span>
                <!-- <span>{{name}}</span> -->
                <div>
                  <!-- <view-linked-info :linkKey="'Report-detail-'+$getQuery('pageid')"></view-linked-info> -->
                </div>
              </template>
            </li>
            <template v-if="Array.isArray(appResourceList)&&appResourceList.length>0">
              <el-submenu :index="String(index)"
                          v-for="(item,index) in ['Dashboards','Bots','Settings']"
                          style="margin-right:20px"
                          :key='index'
                          :disabled="menus(index).length===0"
                          class="menu-item-submenu-item">
                <template slot="title">{{item}}</template>
                <el-menu-item v-for="(itemSub,i) in menus(index)"
                              :key="index+'-'+i"
                              :index="itemSub.resourcePath === 'users-setting' ? 'users-setting' :index+'-'+i">
                  <!-- <el-tooltip :open-delay="1000" placement="top" :content="itemSub.resourceName"> -->
                  <div class="more_text_app"
                       style="width:100%"
                       @click="handleSelect(itemSub)">{{ itemSub.resourceName}}</div>
                  <!-- </el-tooltip> -->
                </el-menu-item>
              </el-submenu>
            </template>
            <template v-else
                      v-for="(item,index) in gadgetSetting.menuList">
              <el-submenu :index="String(index)"
                          :key='index'
                          v-if="item.children&&item.children.length>=1"
                          class="menu-item-submenu-item">
                <template slot="title">
                  <el-tooltip :open-delay="1000"
                              class="item"
                              effect="dark"
                              :content="item.description"
                              placement="top-start"
                              v-if='item.description'>
                    <span @click="headerUrl(item,index)">{{ item.title }}</span>
                  </el-tooltip>
                  <span v-else
                        @click="headerUrl(item,index)">{{ item.title }}</span>
                </template>
                <el-menu-item v-for="(itemSub,i) in item.children"
                              :key="index+'-'+i"
                              :index="index+'-'+i">
                  <el-tooltip :open-delay="1000"
                              class="item"
                              effect="dark"
                              :content="itemSub.description"
                              placement="top-start"
                              v-if='itemSub.description'>
                    <span @click="headerUrl(itemSub,index,i)">{{ itemSub.title }}</span>
                  </el-tooltip>
                  <span v-else
                        @click="headerUrl(itemSub,index,i)">{{ itemSub.title }}</span>
                </el-menu-item>
              </el-submenu>

              <el-menu-item v-else
                            :index="String(index)"
                            :key="String(index)"
                            class="menu-item-submenu">
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="item.description"
                            placement="top-start"
                            v-if='item.description'>
                  <span @click="headerUrl(item,index)">{{ item.title }}</span>
                </el-tooltip>
                <div v-else>
                  <span v-if="item.menuIcon"
                        class="cuifont"
                        :class="item.menuIcon"
                        style="margin:0"
                        :style="{fontSize:item.iconFt}"></span>
                  <span @click="headerUrl(item,index)">{{ item.title }}</span>
                </div>

              </el-menu-item>
            </template>
            <!-- <el-menu-item index="user-setting">
              <SettingBtn />
            </el-menu-item> -->
            <template v-if="isBotDetailPage">
              <div class="bot-css"
                   v-only-clone="$store.getters.botDetail">
                <el-tooltip :open-delay="1000"
                            :content="$t('custom.dataset.editbtn')"
                            placement="top">
                  <i v-if="$hasPermission('sys:bots:edit')"
                     @click="editBots"
                     class="cuifont icon_edit"></i>
                </el-tooltip>
                <!-- <el-tooltip :open-delay="1000" :content="$t('custom.dataset.publishbtn')"
                            placement="top">
                  <i v-if="$hasPermission('sys:bots:design:push')"
                      @click="publishBot"
                      class="cuifont icon_push"></i>
                </el-tooltip> -->
                <!-- <el-tooltip :open-delay="1000" content="Turn Off"
                        placement="top">
              <i class="cuifont icon_power"></i>
            </el-tooltip> -->
                <el-tooltip :open-delay="1000"
                            :content="$t('custom.dataset.deletebtn')"
                            placement="top">
                  <i v-if="$hasPermission('sys:bots:delete')"
                     v-loading="deleteLoading"
                     @click="deleteBots()"
                     class="cuifont icon_delete"></i>
                </el-tooltip>
              </div>
            </template>
            <template v-else>
              <div style="margin-top:10px;" >
                <el-button style="margin-right:5px;"
                          class="design-button"
                           type="success"
                           size="mini"
                           v-if="isShowClone && this.businessType === 'Template' && !hasEditPermission"
                           @click="cloneReport">
                  Design
                </el-button>
                <el-button style="margin-right:5px;"
                        class="design-button"
                           type="success"
                           size="mini"
                           v-else-if="!showMsg&&hasEditPermission"
                           @click="showDesign">
                  Design
                </el-button>

                <el-button-group v-if="showMsg">
                  <el-button style="height: 24px;"
                             size="mini"
                             type="danger"
                             @click="addWidget">{{ 'Add Widget' }}
                  </el-button>
                  <el-button size="mini"
                             style="height: 24px;"
                             type="primary"
                             @click="saveLayout">{{'Save Dashboard'}}
                  </el-button>
                  <el-button size="mini"
                             type=""
                             style="height: 24px;"
                             @click="cancelLayout">{{'Cancel'}}
                  </el-button>
                </el-button-group>

              </div>
              <div style="display: flex;justify-content:flex-end;margin-left:20px">
                <el-tooltip v-if="$hasPermission('sys:report:homepage')&&!$route.path.includes('report-')"
                            effect="dark"
                            :content="$t('custom.component.viewComponent.homepage')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             @click="homepageHandle"><i  class="cuifont icon_home_add"></i>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="hasEditPermission"
                            effect="dark"
                            content="Edit"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             @click="editHandle"><i  class="cuifont icon_edit"></i>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="$hasPermission('sys:report:zoom:setting')&&($route.path.includes('/dashboard-')||$route.path.includes('/present'))"
                            effect="dark"
                            content="Setting"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             @click="settingHandle"><i  class="cuifont icon_settings"></i>
                  </el-button>
                </el-tooltip>
                <!-- <el-tooltip :open-delay="1000"
                            v-if="gadgetSetting.nextTiketPage&&$hasPermission('sys:nextticket:filter')"
                            effect="dark"
                            :content="$t('custom.filter')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             @click="filterHandle"><i  class="cuifont icon_filter"></i>
                  </el-button>
                </el-tooltip> -->
                <div>
                  <el-popover ref="autorefresh-popover"
                              placement="bottom"
                              width="300"
                              :disabled="$route.path === '/home'"
                              trigger="hover"
                              :open-delay="openDelay"
                              style="">
                    <div v-loading="autoRefreshloading">
                      <el-checkbox v-model="isAutoRefresh"
                                   style="margin-bottom: 10px;">{{$t('custom.dataset.enableRefresh')}}</el-checkbox>
                      <el-radio-group v-model="minuteNumber"
                                      :disabled="!isAutoRefresh">
                        <el-radio style="margin:5px"
                                  :label="3">3 Minutes</el-radio>
                        <el-radio style="margin:5px"
                                  :label="5">5 Minutes</el-radio>
                        <el-radio style="margin:5px"
                                  :label="10">10 Minutes</el-radio>
                      </el-radio-group>
                      <div>
                        {{$t('custom.bots.design.refreshInEvery')}}&nbsp;<el-input-number :disabled="!isAutoRefresh"
                                         v-model="minuteNumber"
                                         :min="3"
                                         placeholder=""
                                         @input="changeNumber"
                                         style="margin-bottom: 10px;width:35%;"
                                         size="mini">
                        </el-input-number> {{$t('custom.component.gadget.timeMinutes')}}
                      </div>
                      <el-button type="primary"
                                 :disabled="autoRefreshloading"
                                 @click.stop="updateSetting"
                                 size="mini">{{$t('custom.component.gadget.submit')}}</el-button>
                    </div>
                    <el-button style="margin-left:5px;margin-right:5px;margin-top: 3px;"
                               slot="reference"
                               type="text">
                      <el-tooltip :open-delay="1000"
                                  class="item"
                                  effect="dark"
                                  :content="$route.path === '/home'?$t('custom.component.gadget.refreshAllWdiget'):$t('custom.component.gadget.refreshAllText')"
                                  placement="top">
                        <i  class="cuifont icon_arrow_sync"
                           v-if="gadgetSetting.showRefresh"
                           style=""
                           @click="refreshQurey"></i>
                      </el-tooltip>
                    </el-button>
                  </el-popover>
                </div>

                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="$t('custom.component.gadget.cloneReport')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             v-if="isShowClone && !(this.businessType === 'Template' && !hasEditPermission)"
                             @click="cloneReport"><i class="cuifont icon_copy"></i>
                  </el-button>
                </el-tooltip>
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="$t('custom.component.gadget.shareReport')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             v-if="isShowShare"
                             @click="ShareReport"><i  class="cuifont icon_share"></i>
                  </el-button>
                </el-tooltip>

                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="$t('custom.component.viewComponent.delete')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             v-if="isShowDelete"
                             @click="deleteReport"><i  class="cuifont icon_delete"></i>
                  </el-button>
                </el-tooltip>
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="$t('custom.component.gadget.showScorecard')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             v-if="isShowSwtichLayout"
                             @click="showScoreCardLayout"><i  class="cuifont icon_goal"></i>
                  </el-button>
                </el-tooltip>
                <div v-if="isShowPresentMode">
                  <el-popover ref="present-popover"
                              placement="bottom"
                              width="200"
                              trigger="hover"
                              style="">
                    <div>
                      <ul>
                        <li @click="presentModeChange('single',{reportId:''})"
                            class="el-select-dropdown__item cursor-pointer"
                            style="padding:0px">
                          <i class="cuifont icon_window"
                             style="font-size:14px;margin-left:-5px;"></i>{{$t('custom.component.gadget.singleDashboard')}}
                        </li>
                        <li @click="presentModeChange('rotate',{reportId:''})"
                            class="el-select-dropdown__item cursor-pointer"
                            style="padding:0px;">
                          <i class="cuifont icon_windows"
                             style="font-size:14px;margin-left:-5px;"></i>{{$t('custom.component.gadget.rotateDashboard')}}
                        </li>
                        <li @click="ShareReport('showTV')" v-if="isShowShareToTV"
                            class="el-select-dropdown__item cursor-pointer"
                            style="padding:0px;">
                          <i class="cuifont icon_tv"
                             style="font-size:14px;margin-left:-5px;"></i>{{$t('custom.component.shareLinkDialog.streamToTv2')}}
                        </li>
                      </ul>
                    </div>
                    <el-button style="margin-left:5px;margin-right:5px;margin-top: 3px;"
                               slot="reference"
                               type="text">
                      <el-tooltip :open-delay="1000"
                                  class="item"
                                  effect="dark"
                                  :content="'Presentation'"
                                  placement="top-start">
                        <i  class="cuifont icon_slideshow"
                           style=""></i>
                      </el-tooltip>
                    </el-button>
                  </el-popover>
                </div>
                <el-tooltip :open-delay="1000"
                            class="item"
                            effect="dark"
                            :content="$t('custom.component.gadget.exportPDF')"
                            placement="top-start">
                  <el-button style=""
                             type="text"
                             v-loading="pdfLoading"
                             v-if="isShowExportPDF"
                             @click="handleExportPDF"><i class="cuifont icon_a-DocumentPDF"></i>
                  </el-button>
                </el-tooltip>
              </div>
            </template>
          </el-menu>
        </div>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <AddUpdate ref="addUpdateForm"
               :botType="botType"
               :editType="'botDetails'"
               :parentStateObj="botTem"
               @refreshList="query"
               @reselectTemplate="reselectTemplateFn"></AddUpdate>
    <SelectBotTemplate ref="addUpdateObjTem"
                       @showDataForm="jumpDataForm"></SelectBotTemplate>
    <PublishBot ref="publish-bot" />
    <add-new-report ref="addNewReport"
                    :presentModeItem="presentModeItem">
    </add-new-report>
    <PresentManagement ref="presentManagement"
                       v-if="presentManage"
                       @changeDashboard="addReportPop" />
    <HomePageDialog ref="HomePageDialog"></HomePageDialog>
    <AttendanceOptionsDialog ref="attendanceOptionsDialog" />
    <el-dialog title="Setting"
               :visible.sync="settingDialogVisible"
               width="30%"
               append-to-body
               @close="handleClose">
               <el-form>
                  <el-form-item label="Fit widget size to match page height:">
                    <el-checkbox v-model="fitToHeightVal"></el-checkbox>
                  </el-form-item>
                  <!-- <el-form-item label="TV Show Page Header">
                    <el-switch v-model="value"></el-switch>
                  </el-form-item> -->
               </el-form>
     
      <span slot="footer"
            class="dialog-footer">
        <el-button size="mini"
                   @click="settingDialogVisible = false">Cancel</el-button>
        <el-button size="mini"
                   type="primary"
                   @click="saveSetting">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { getUrlQureyParams, currentTabRemoveHandle } from '@/utils/common'
import { getUUID } from '@/utils'
import { dashboardGadgetList, defaultGadgetSettingList } from '@/utils/data-json'
import AddUpdate from '@/views/modules/mspbots/bots-bak/my-bots/add-or-update-bak'
import PublishBot from '@/views/modules/mspbots/bots-bak/bot-template/publish-bot'
import SelectBotTemplate from '@/views/modules/mspbots/bots-bak/my-bots/select-bot-tempalte'
import AttendanceOptionsDialog from '@/components/storybook/b-dialog-pay/attendance-options-dialog'
import { LinkComponent } from '@/views/modules/mspbots/bots-bak/my-bots/BotFormatComponents/LinkComponent.js'
import AddNewReport from '@/views/modules/mspbots/reports/add-new-report'
import { isNumber } from '@/utils/validate'
import store from '@/store'
import PresentManagement from './components/present-management'
import Cookies from 'js-cookie'
import HomePageDialog from '@/components/homepage-dialog/homepage-dialog.vue'
/* eslint-disable */
import { PayContext } from '@/components/storybook/s-pay/pay-context'
import { getUrl } from '@/components/storybook/utilties/chargebee'
import { sqlSet } from '@/components/storybook/utilties/throttleRequest'
import { debounce ,throttle } from 'lodash'
import Vue from 'vue'
import JsPDF from 'jspdf'
import html2canvas from 'html2canvas'

import bus from '@/components/storybook/utilties/bus'

import html2pdf from 'html2pdf.js'
import { deleteBotInfoApi } from '@/api/new'

import JsFileDownload from 'js-file-download'
export default ({
  mixins: [mixinGadgetViewModule],
  components: { AddUpdate, PublishBot, SelectBotTemplate, AddNewReport, PresentManagement, HomePageDialog, AttendanceOptionsDialog, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      pdfLoading: false,
      MessageInterval: null,
      gadgetSetting: {},
      gadgetStatus: 'init',
      loading: false,
      autoRefreshloading: false,
      thisGadgetid: '',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'pageheadergadget',
          gadgetSetting: null
          // gadgetSetting: {
          //   icon: 'cuifont icon_help_circle',
          //   haderImg: 'https://oss.mspbots.ai/app/gadget/page-header-gadget.png',
          //   headerTitleFontSize: '16px',
          //   headerTitleFontColor: '#000',
          //   headerTitle: '',
          //   headerDescription: null,
          //   menuList: [],
          //   filters: [],
          //   slicer: {},
          //   filtersList: [],
          //   filtersGroupName: ''
          // }
        }
      },
      filtersShow: false,
      pageFilterList: [],
      pageGadgetList: [],
      pageGadgets: [],
      filtersGroupName: '',
      renameVisible: false,
      showMsg: false,
      botDetailInfo: {},
      botTem: -1,
      botType: '',
      deleteLoading: false,
      minuteNumber: 3,
      isAutoRefresh: false,
      minList: [3, 5, 10],
      timers: null,
      openDelay: 2000,
      appResourceList: [],
      presentManage: false,
      stopAutoRefreshParam: true,
      settingDialogVisible: false,
      fitToHeightVal: false
    }
  },
  watch: {
    filtersShow (val) {
      if (val) {
        this.getPageFilterList()
      }
    }
  },
  props: ['settingForm', 'editMode', 'totalPages'],
  created () {
    Vue['_this'] = this
    this.queryModelDefaultSetting.dataInfo.gadgetSetting = this._.find(defaultGadgetSettingList, { gadgetType: 'pageheadergadget' }).gadgetSetting
    this.initBot()
    const clonewidget = JSON.parse(localStorage.getItem(`cloneWightToDashboards-${this.pageId}`))
    if(clonewidget && clonewidget.id) { 
       this.showDesign()
      }
    this.$root.eventBus.$on('event:handleAssignALicense', () => {
      if (this.menus(2).find(v => v.resourcePath === 'users-setting')) {
        PayContext.payModal = 'setting'
      } else {
        this.$message({
          message: "You don't have permission yet!",
          type: 'warning',
          center: true
        });
      }
    })
    if (this.editMode) {
      this.showDesign()
    }
  },
  activated () {
    localStorage.getItem('botnamefordetailpage') && this.$set(this.botDetailInfo, 'botName', localStorage.getItem('botnamefordetailpage'))
    window.addEventListener('message', this.messageEvent)
    const clonewidget = JSON.parse(localStorage.getItem(`cloneWightToDashboards-${this.pageId}`))
    if(clonewidget && clonewidget.id) { 
       this.showDesign()
      }
  },
  deactivated () {
    window.removeEventListener('message', this.messageEvent)
    // clearInterval(this.timers)
  },
  beforeDestroy () {
    this.$root.eventBus.$off('event:handleAssignALicense')
    window.removeEventListener('message', this.messageEvent)
    clearInterval(this.timers)
  },
  computed: {
 
    isBotDetailPage () {
      if (window.location.pathname.includes('bot-')) {
        return true
      } else {
        return false
      }
    },
    activeIndex () {
      var temp
      var pageid = this.$route.query.pageid
      var botId = this.$route.query.botId
      if (this.appResourceList) {
        var res = this.appResourceList.find(i => i.resourceId === pageid)
        if (res) {
          ['Dashboards', 'Bot', 'Setting'].forEach((item, index) => {
            if (res.resourceMenu === (index + 1)) {
              var index2 = this.appResourceList.filter(i => i.resourceMenu === res.resourceMenu).findIndex(item => item.resourceId === res.resourceId)
              if (index2 || index2 === 0) {
                temp = index + '-' + index2
              }
            }
          })
        } else {
          var resIndex = this.appResourceList.filter(item => item.resourceMenu === 2).findIndex(i => i.resourceId === botId)
          temp = `1-${resIndex}`
        }
      }
      return String(temp)
    },
    pageFiltersList () {
      let temp = []
      let filterLists = this.pageFilterList
      let gadgetLists = this.pageGadgetList
      let nowPageGadgets = this.pageGadgets

      const getName = gadgetId => {
        try {
          return gadgetLists.find(e => e.gadgetId === gadgetId).name
        } catch (error) {
          return null
        }
      }
      const getFilterSql = gadgetId => {
        try {
          return filterLists.find(e => e.gadgetId === gadgetId).filterSql
        } catch (error) {
          return null
        }
      }
      const getMoreMenuList = key => {
        try {
          return dashboardGadgetList.find(e => e.key === key).moreMenu.menuList
        } catch (error) {
          return []
        }
      }
      for (let i = 0; i < nowPageGadgets.length; i++) {
        if (getMoreMenuList(nowPageGadgets[i].com).some(e => e.type === 'filter')) {
          if (getFilterSql(nowPageGadgets[i].i)) {
            temp.push({
              gadgetId: nowPageGadgets[i].i,
              filterSql: getFilterSql(nowPageGadgets[i].i),
              gadgetName: getName(nowPageGadgets[i].i)
            })
          }
        }
      }
      if (temp.length === 0) {
        temp.push({
          gadgetId: null,
          filterSql: null,
          gadgetName: null
        })
      }
      return temp
    },
    hasEditPermission () {
      let temp = false
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let editAuth = this.$hasPermission('sys:report:edit') ? 1 : 0
      let isCustom = this.businessType === 'Custom' ? 1 : 0
      if (reportadmin + editAuth + isCustom >= 2) {
        temp = true
      } else {
        temp = false
      }
      if (this.presentModeItem) {
        temp = false
      }
      return temp
    },
    reportName () {
      if (this.reportNameForPage) {
        return this.reportNameForPage
      } else {
        return ''
      }
    },
    isShowClone () {
      let temp = false
      let path = window.location.pathname
      if ((path.includes('dashboard-') || path.includes('scorecard-')) && this.$hasPermission('sys:report:clone') && isNumber(this.pageId) && this.gadgetSetting.showClone) {
        temp = true
      }
      if (this.$route.path === '/home' && this.$hasPermission('sys:report:clone') && this.gadgetSetting.showClone) {
        temp = true
      }
      if (this.presentModeItem) {
        temp = false
      }
      if ((this.$route.query.hasOwnProperty('clonable') && !this.$route.query.clonable) || !this.clonable()) {
        temp = false
      }
      return temp
    },
    isShowShare () {
      let dashboardsDetailsData = this.dashboardsDetailsData()
      return this.$hasPermission(`sys:report:share`) && dashboardsDetailsData.businessType !== 'Template' && dashboardsDetailsData.type !== 100101
    },
    isShowDelete () {
      let temp = false
      let path = window.location.pathname
      if ((path.includes('report-') || path.includes('dashboard-') || path.includes('scorecard-')) && this.$hasPermission('sys:report:delete') && isNumber(this.pageId)) {
        temp = this.hasDeletePermission()
      }
      if (this.$route.path === '/home' && this.$hasPermission('sys:report:delete')) {
        temp = true
      }
      if (this.presentModeItem) {
        temp = false
      }
      return temp
    },
    isShowSwtichLayout () {
      let temp = false
      if (this.layoutType && this.layoutType === 'scorecard_layout') {
        temp = true
      }
      if (this.presentMode) {
        temp = false
      }
      return temp
    },
    isShowPresentMode () {
      let temp = false
      if (this.presentMode) {
        temp = true
      }
      if (this.presentModeItem) {
        temp = false
      }
      if (Cookies.get('loginSource') && Cookies.get('loginSource') === 'portal') {
        temp = false
      }
      if (this.$route.path.includes('report-')) {
        temp = false
      }
      return temp
    },
    isShowExportPDF () {
      return this.$route.path.includes('report-')
    },
    comGridMaxNum () {
      if(window.SITE_CONFIG['dictList'].find(e => e.dictType === 'PDF_grid_max_num')&&window.SITE_CONFIG['dictList'].find(e => e.dictType === 'PDF_grid_max_num').dataList){
        return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'PDF_grid_max_num').dataList[0].dictValue
      }
      return 350
    },
    downloadPdfList () {
      return this.$store.state.app.downloadPdfList
    },
    isShowShareToTV() {
      let _this = this
      if(this.businessType === 'Custom') {
        return true
      }
      try {
        if(!_this.$hasPermission('sys:tv:share:template:dashboard')) {
          return false
        }
        if(_this.$store.state.nextTicket.nextTicketAppList.some(i=>i.appParam.resourceId === _this.pageId)) {
          return false
        }
        return true
      } catch (error) {
        
      }
    }
  },

  methods: {
    ShareReport (type) {
      bus.$emit('Dashboards-Share', true,type)
    },
    saveSetting() {
      this.$emit('update:fitToHeight',this.fitToHeightVal)
      this.publishMessage('showEditMode')
      this.saveLayout('fitToHeight')
      this.settingDialogVisible = false
    },
    handleClose () {
      this.fitToHeightVal = false
    },
    messageEvent (event) {
      if (event.data.message) {
        if (this.MessageInterval) {
          clearInterval(this.MessageInterval)
        }
      }


    },
    async getAppInfo () {
      try {
        if (this.$route.query.appId) {
          const { getAppInfoApi } = this.$interface.reports
          const params = { id: this.$route.query.appId }
          let { data: response } = await getAppInfoApi(params)
          if (response.code !== 0) {
            this.appResourceList = JSON.parse(sessionStorage.getItem('appResourceList'))
            throw response.msg
          }
          this.appResourceList = response.data.appResourceList
        }
      } catch (err) {
        this.appResourceList = JSON.parse(sessionStorage.getItem('appResourceList'))
      }
    },
    menus (index) {
      return this.appResourceList.filter(i => {
        if (i.resourcePath === 'users-setting' && i.resourceMenu === (index + 1)) {
          return this.$hasPermission('pay:users-setting')
        } else {
          const bol = this.$hasPermission('sys:attendance:options')
          return i.resourceMenu === (index + 1) && (i.resourceName === 'Options' ? bol : true)
        }
      })
    },
    homepageHandle () {
      if (this.$route.path === '/home') {
        this.$refs.HomePageDialog.init({ id: this.$store.state.user.homePage })
      } else {
        this.$refs.HomePageDialog.init({ id: this.$route.query.pageid })
      }
    },
    hasDeletePermission () {
      let reportadmin = this.$hasPermission('sys:report:reportadmin') ? 1 : 0
      let deleteAuth = this.$hasPermission('sys:report:delete') ? 1 : 0
      let isCustom = this.businessType === 'Custom' ? 1 : 0
      if (reportadmin + deleteAuth + isCustom >= 2) {
        return true
      } else {
        return false
      }
    },
    deleteReport () {
      if (!this.$hasPermission('sys:report:delete') || !this.$hasPermissionRouterName(('report-' + this.reportName).replace(/ /g, ''))) {
        return this.$message.error(this.$t('prompt.nopermission'))
      }
      this.$confirm(this.$t('custom.apps.deleteconfirm'), this.$t('custom.apps.warning'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.doDeleteReport(this.pageId)
      })
    },
    doDeleteReport (id) {
      const params = {
        id: id
      }
      this.$interface.reports.delReportsForPageheaderApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success('Success')
          currentTabRemoveHandle(store.state.contentTabsActiveName)
          this.$root.eventBus.$emit('deleteReport')
        })
        .catch(() => { })
    },
    selectHander (index, indexPath) {
      if (index !== 'users-setting') {
        this.initBot()
      }
    },
    newReport (data) {
      var newobj = {
        'id': '1338420673936867329',
        'type': 2,
        'tenantCode': null,
        'name': '',
        'businessId': '1f19d393-98e6-4dfb-84ce-2f1a46d64286',
        'businessType': 'Template',
        'content': null,
        'gadgetId': null,
        'language': null,
        'data': null,
        'integration': '',
        'description': '',
        'status': 'In-Dev',
        'creator': null,
        'creatorName': null,
        'exist': false,
        'showAllIntegration': false
      }
      if (data) {
        newobj.id = data
      }
      this.$nextTick(() => {
        this.$refs.addNewReport.dataForm.id = newobj.id
        this.$refs.addNewReport.init()
      })
    },
    editHandle () {
      var reportName = this.$route.query.name
      var id = this.$route.query.pageid || (this.$store.state.user.homePage || 'home')
      if (!this.hasEditPermission || !this.$hasPermissionRouterName(('report-' + reportName).replace(/ /g, ''))) {
        return this.$message.error(this.$t('prompt.nopermission'))
      }
      this.newReport(id)
      this.$refs.addNewReport.visible = true
    },
    settingHandle () {
      this.fitToHeightVal = this.fitToHeight
      this.settingDialogVisible = true
    },
    initBot () {
      // this.getAppResourceList()
      this.getAppInfo()
      this.gadgetHeight = (this.gadgetInfo.h * 20) - 20
      this.subscribeMessage('gadgetremoved', this.removeFilter)
      this.query()
      this.isBotDetailPage ? this.setBotDetailInfo() : null
      this.$store.state.isWidget = false
      this.gadgetMessageBus.$on(this.pageId + 'showDesign', (e) => { this.showDesign() })
      this.gadgetMessageBus.$on(this.pageId + 'changeBotName', (e) => { this.changeBotName() })
      this.gadgetMessageBus.$on(this.pageId + 'closeLoading', (e) => {
        this.closeLoading()
      })
      this.gadgetMessageBus.$on(this.pageId + 'emitselectedgadgetPop', e => { 
        this.emitselectedgadgetPop() 
      })
      this.gadgetMessageBus.$on(this.pageId + 'stopautorefresh', e => { 
        this.stopAutoRefresh() 
      })
    },
    stopAutoRefresh () {
      if (this.isAutoRefresh) {
        // this.isAutoRefresh = false
        // this.stopAutoRefreshParam = true
        // clearInterval(this.timers)
        // this.timers = null
        // this.updateSetting()
      }
    },
    closeLoading () {
      this.loading = false
    },
    async handleSelect (item) {
      if (item.resourcePath === 'users-setting') {
        PayContext.payModal = 'setting'
        return
      } else if (item.resourcePath === 'attendance-options') {
        this.$refs.attendanceOptionsDialog.dialogVisible = true
        return
      }


      if (item.resourceType === 1) {
        const route = getUrl(`/dashboard-${item.resourceId}`, {
          pageid: item.resourceId,
          name: item.resourceName,
          // appResourceList: JSON.stringify(this.appResourceList),
          appId: item.appId,
          subscriptionId: item.subscriptionId,
          subscriptionStatus: item.subscriptionStatus,
          layout: item.layoutType || 'report_layout'
        })
        this.$router.push(route)
      } else if (item.resourceType === 2) {
        const route = getUrl(`bot-${item.resourceId}`, {
          pageid: 'botdetail',
          botId: item.resourceId,
          name: item.resourceName,
          // appResourceList: JSON.stringify(this.appResourceList),
          appId: item.appId,
          subscriptionId: item.subscriptionId,
          subscriptionStatus: item.subscriptionStatus,
        })
        this.$router.push(route)
      } else if (item.resourceType === 3) {
        if (item.resourcePath.includes('http') || item.resourcePath.includes('https')) {
          const route = getUrl(item.resourcePath, {
            appId: item.appId,
            name: item.resourceName,
            subscriptionId: item.subscriptionId,
            subscriptionStatus: item.subscriptionStatus
          })

          window.open(route.path, '_blank')
        } else {
          const route = getUrl(item.resourcePath, {
            appId: item.appId,
            name: item.resourceName,
            subscriptionId: item.subscriptionId,
            subscriptionStatus: item.subscriptionStatus
          })
          this.$router.push(route)
        }
      }

    },
    closeCurrentTab () {
      var tabName = this.$store.state.contentTabsActiveName
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== tabName)
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
        return false
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        this.$router.push({ name: this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1].name })
      }
    },
    getAppResourceList () {
      try {
        if (this.$route.query.appResourceList[0] !== '[object Object]') {
          this.appResourceList = JSON.parse(this.$route.query.appResourceList)
        } else {
          this.appResourceList = JSON.parse(sessionStorage.getItem('appResourceList'))
        }
      } catch (error) {

      }
    },
    selectMin (val) {
      if (val) {
        this.minuteNumber = val
      }
    },
    autoRefresh (val, minuteNumber) {
      if (val && minuteNumber && Number(minuteNumber) > 0) {
        // this.publishMessage('runReport')
        this.timers = setInterval(() => {
          sqlSet.clear()
          var hidden
          if (typeof document.hidden !== "undefined") {
            hidden = "hidden";
          } else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden";
          } else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden";
          } else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden";
          }
          if (!document[hidden]) {
            if (window.location.pathname !== '/home' && (this.$store.state.sidebarMenuActiveName && (this.$store.state.sidebarMenuActiveName.includes(this.pageId))) || window.location.pathname === '/portalDashboard' || window.location.pathname === '/portalPageDashboard' || window.location.pathname === '/publicReport' || window.location.pathname === '/publicReportPdf' || window.location.pathname === '/present') {
              this.publishMessage('runReport')
            }
          }
        }, Number(minuteNumber) * 60000)
      } else {
        clearInterval(this.timers)
      }
    },
    changeNumber (val) {
      if (val > 3) {
        val = 3
      }
    },
    cloneReport () {
      const row = {
        id: this.pageId,
        businessType: this.businessType
      }
      this.$nextTick(() => {
        this.$refs.addNewReport.dataForm.id = row.id
        this.$refs.addNewReport.init()
        this.$refs.addNewReport.cloneShow(row)
      })
    },
    showDesign () {
      this.showMsg = true
      this.publishMessage('showEditMode')
    },
    cancelDesign () {
      this.showMsg = !this.showMsg
      this.publishMessage('hideEditMode')
    },
    showScoreCardLayout () {
      this.publishMessage('isShowGridLayout')
    },
    addWidget () {
      this.publishMessage('addgauge')
    },
    saveLayout (type) {
      this.$emit('before-save')
      this.loading = true
      this.publishMessage('toggleClick',null,type)
      localStorage.removeItem(`cloneWightToDashboards-${this.pageId}`)
      bus.$emit('event:refresh-widget-list')
    },
    cancelLayout () {
      this.$confirm(
        this.$t('prompt.para', { handle: 'By clicking on this button, all the changes to this dashboard will be revert back last saved state.' }), 'Warning', {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(async () => {
          this.cancelDesign()
          this.$store.state.contentIsNeedRefresh = true
          this.$nextTick(() => {
            this.$store.state.contentIsNeedRefresh = false
          })
          let cloneWidget = JSON.parse(localStorage.getItem(`cloneWightToDashboards-${this.pageId}`))
          if (cloneWidget&&cloneWidget.id) {
            this.onDelete(cloneWidget)
          }
          localStorage.removeItem(`cloneWightToDashboards-${this.pageId}`)
          bus.$emit('event:refresh-widget-list')
        }).catch((error) => {
          console.log(error);
        })
    },
    async onDelete (data) {
      try {
        const params = {
          id: data.id
        }

        const { delReportSetting } = this.$interface.reports
        const { data: response } = await delReportSetting(
          params,
          1
        )
        if (response.code !== 0) {
          throw response.msg
        }
      } catch (error) {
        console.log(error);
      } finally {
      }
    },
    getPageFilterList () {
      try {
        if (this.pageGadgetList.length <= 0) {
          this.getAllGadgetList()
        }
        if (this.pageGadgets.length <= 0) {
          this.getPageGadgetList()
        }
        this.getAllFilterList()
      } catch (error) {
        this.getAllFilterList()
      }
    },
    getAllFilterList () {
      const params = {
        pageId: this.$getQuery('pageid')
      }
      this.$interface.reports.getFilterListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.pageFilterList = res.data
        })
        .catch(() => { })
    },
    getAllGadgetList () {
      const params = {
        businessId: $getQuery('pageid')
      }
      this.$interface.reports.getReportDataListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.pageGadgetList = res.data
          }
        })
        .catch(() => { })
    },
    getPageGadgetList () {
      const params = {
        businessId: this.$getQuery('pageid')
      }
      this.$interface.reports.getDashboardLayout(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.pageGadgets = ((res.data.contentNew && res.data.contentNew.length) > 0 ? res.data.contentNew : JSON.parse(res.data.content)) || []
          }
        })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 20
      this.gadgetWidth = newWPx
    },
    updateSetting () {
      if (this.isAutoRefresh) {
        if (!this.minuteNumber) {
          return this.$message.error('Please set refresh Time')
        }
      }
      clearInterval(this.timers)
      this.autoRefreshloading = true
      if (this.gadgetSetting.report) {
        this.gadgetSetting.report.minuteNumber = this.minuteNumber
        this.gadgetSetting.report.isAutoRefresh = this.isAutoRefresh
      } else {
        this.gadgetSetting.report = {}
        this.gadgetSetting.report.minuteNumber = this.minuteNumber
        this.gadgetSetting.report.isAutoRefresh = this.isAutoRefresh
      }
      const params = {
        gadgetId: this.id,
        gadgetSetting: this.gadgetSetting,
        tenantLog: {
          operationGroup: 2,
          operationType: 6,
          businessId: this.pageId,
          operation: {
            autoRefreshSwtich: this.gadgetSetting.report.isAutoRefresh
          }
        }
      }
      this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        this.autoRefreshloading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data.gadgetSetting.report.isAutoRefresh && res.data.gadgetSetting.report.minuteNumber && res.data.gadgetSetting.report.minuteNumber > 0) {
          this.publishMessage('runReport')
          this.autoRefresh(res.data.gadgetSetting.report.isAutoRefresh, res.data.gadgetSetting.report.minuteNumber)
        }
        if (this.$refs['autorefresh-popover']) this.$refs['autorefresh-popover'].doClose()
      }).catch(() => {
        this.autoRefreshloading = false
      })
    },
    query () {
      this.loading = true
      this.gadgetSetting.menuList = []
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)

      var _self = this
      var param = {
        ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id
      }
      if (getUrlQureyParams('appId')) {
        param.appId = getUrlQureyParams('appId')
      }
      clearInterval(this.timers)
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        if (res.config) {
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        }
        _self.minuteNumber = _self.gadgetSetting.report && _self.gadgetSetting.report.minuteNumber ? _self.gadgetSetting.report.minuteNumber : 3
        _self.isAutoRefresh = _self.gadgetSetting.report && _self.gadgetSetting.report.isAutoRefresh ? _self.gadgetSetting.report.isAutoRefresh : false
        const activeViewName = localStorage.getItem('pageheadergadget_activeViewName')
        const activeGadget = _self.gadgetSetting.filtersList.find(item => item.name === activeViewName)
        if (activeGadget) {
          _self.gadgetSetting.filters = activeGadget.filters
        }
        if (_self.gadgetSetting.filters) {
          _self.gadgetSetting.filters.forEach(item => {
            if (item) {
              _self.addFilter(item.gadgetid, item.filter)
            }
          })
        }
        if (_self.isAutoRefresh && _self.minuteNumber) {
          _self.autoRefresh(_self.isAutoRefresh, _self.minuteNumber)
        }

        this.loading = false
      }).catch(() => {
        this.loading = false
      }).finally(() => {
        this.loading = false
        _self.updateGadgetStatus('ready')
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    headerUrl (item, index, i) {
      if (!item || !item.name) {
        return
      }
      if (i > -1) {
        if (this.activeIndex === `${index}-${i}`) {
          return
        }
      } else {
        if (this.gadgetSetting.menuList[this.activeIndex] === item) {
          return
        }
      }
      if (item.path.includes('bot-')) {
        if (this.$route.query && this.$route.query.botId && this.$route.query.botId === item.query.botId) {
          return
        }
        if (this.$route.path && this.$route.path === item.path) {
          this.publishMessage('botDetailReload', item)
        }
      }
      if (!item.isReplace) this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== this.$store.state.contentTabsActiveName)
      const menu = {
        name: item.name,
        params: { ...item.params },
        query: { ...item.query }
      }
      
      this.$router.replace({ ...menu })
    },
    refreshQurey :throttle(function () {
      const _self = this
      sqlSet.clear()
      _self.publishMessage('runReport')
    },20000),
    saveGadgetSetting () {
      const _self = this
      const params = {
        gadgetSetting: this.gadgetSetting,
        gadgetId: this.id
      }
      this.$interface.reports.postReportSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
        _self.gadgetSetting.filters.forEach(item => {
          _self.addFilter(item.gadgetid, item.filter)
        })
        _self.$message.success(res.msg)
      })
    },
    clearCurrentFilter () {
      this.$confirm('Are you sure to clear?')
        .then(async () => {
          this.updateFilterBatch()
        })
        .catch(_ => { })
    },
    updateFilterBatch (filterList = []) {
      const pageid = this.$getQuery('pageid')
      const params = filterList
      for (let index = 0; index < params.length; index++) {
        params[index].pageId = pageid
      }
      this.$interface.reports.putBatchFilterApi(pageid, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          this.refreshQurey()
        })
        .catch(() => { })
    },
    cancelRename () {
      this.filtersGroupName = ''
      this.renameVisible = false
    },
    saveAsNew () {
      if (this.filtersGroupName.length === 0) {
        this.$message.warning('Please enter a name')
      }
      if (this.filtersGroupName) {
        if (this.gadgetSetting.filtersList.some(item => item.name === this.filtersGroupName)) {
          this.$message.warning('Name already exists')
          return false
        }
        const filterObj = {
          id: getUUID(),
          name: this.filtersGroupName,
          filters: this.pageFilterList
        }
        this.gadgetSetting.filtersList.push(filterObj)
        this.cancelRename()
        this.saveGadgetSetting()
      }
    },
    deleteFilterGroups (row) {
      this.$confirm('Are you sure to delete?')
        .then(async () => {
          if (row) {
            let removeIndex = this.gadgetSetting.filtersList.findIndex(e => e.id === row.id)
            if (removeIndex !== -1) {
              this.gadgetSetting.filtersList.splice(removeIndex, 1)
              this.saveGadgetSetting()
            }
          }
        })
        .catch(_ => { })
    },
    applyFilterGroups (row) {
      var _self = this
      if (row) {
        this.$confirm('To apply this filter will override current filter, Are you sure to continue?')
          .then(async () => {
            let filterList = row.filters.map(e => {
              e['id'] = null
              return e
            })
            _self.updateFilterBatch(filterList)
          })
          .catch(() => {
          })
      }
    },
    removeFilter (gadgetid) {
      if (gadgetid) {
        this.gadgetSetting.filters = this.gadgetSetting.filters.filter(item => item.gadgetid !== gadgetid)
        for (let i = 0; i < this.gadgetSetting.filtersList.length; i++) {
          this.gadgetSetting.filtersList[i].filters = this.gadgetSetting.filtersList[i].filters.filter(item => item.gadgetid !== gadgetid)
        }
        this.gadgetSetting.filters.forEach(item => {
          this.addFilter(item.gadgetid, item.filter)
        })
      } else {
        this.gadgetSetting.filters = []
        this.clearFilter()
      }
      this.saveGadgetSetting()
    },

    setBotDetailInfo () {
      try {
        let hasQure = window.location.search.split('?').length > 1
        hasQure && window.location.search.split('?')[1].split('&').map(e => {
          this.$set(this.botDetailInfo, e.split('=')[0], e.split('=')[1])
        })
        this.$set(this.botDetailInfo, 'botName', localStorage.getItem('botnamefordetailpage'))
        this.botDetailInfo.originalId && this.getBotIdByOriginalId(this.botDetailInfo.originalId)
      } catch (error) { }
    },
    botDesign () {
      // this.$router.push({ name: 'mspbots-bots-bak-bot-view-index', query: { botId: this.botDetailInfo.botId } })
      this.$router.push({ name: 'mspbots-bots-bak-bot-design-index', query: { botId: this.botDetailInfo.botId } })
    },
    editBots () {
      this.$nextTick(() => {
        this.$store.commit('BOTFORMEDIT', true)
        this.$refs.addUpdateForm.dataForm.id = this.botDetailInfo.botId
        this.$refs.addUpdateForm.init()
      })
    },
    publishBot () {
      this.$refs['publish-bot'].openDialog(this.botDetailInfo.botId)
    },
    deleteBots: debounce(function () {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.deleteLoading = true
        const params = {
          id: this.botDetailInfo.botId
        }
        deleteBotInfoApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.deleteLoading = false
            return this.$message.error(res.msg)
          }
          let detailIndex = store.state.contentTabs.findIndex(e => e.title === 'Bot Detail')
          if (detailIndex > -1) {
            this.deleteLoading = false
            currentTabRemoveHandle(store.state.contentTabs[detailIndex].name)
          }
          if (this.$store.state.contentTabs.length <= 0) {
            this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
            return false
          }
          this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.menuId !== this.botDetailInfo.botId)
          let tab = this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1]
          this.$router.push({
            path: tab.path,
            params: { ...tab.params },
            query: { ...tab.query }
          })
          LinkComponent.$emit('initPageList')
          return this.$message.success(res.msg)
        }).catch((e) => {
          this.deleteLoading = false
        })
      }).catch(() => {
        this.deleteLoading = false
      })
    }, 1000),
    changeBotName () {
      this.setBotDetailInfo()
    },
    getBotIdByOriginalId (originalId) {
      this.$interface.bots.getBotIdByOriginalId(originalId)
        .then(({ data: res }) => {
          this.$set(this.botDetailInfo, 'botId', res.data)
          this.gadgetSetting[this.gadgetSetting.menuList.findIndex(e => e.originalId === originalId)].query['botId'] = res.data
        })
        .catch(() => { })
    },
    reselectTemplateFn () {
      this.$nextTick(() => {
        this.$refs.addUpdateForm.visible = false
        this.$refs.addUpdateObjTem.visible = true
        this.$refs.addUpdateObjTem.init()
      })
    },
    jumpDataForm (item) {
      this.$refs.addUpdateForm.visible = true
      this.$nextTick(() => {
        // this.$refs.addUpdateForm.dataForm.id = this.botInfo.id
        // this.$refs.addUpdateForm.init()
      })
      this.botTem = item.item
      this.botType = item.type
    },
    presentModeChange (type, data) {
      this.presentManage = true
      if (type === 'single') {
        let routerJump = this.$router.resolve({ path: 'present', query: { queryPresentId: this.pageId, appId: getUrlQureyParams('appId'), name: this.reportName,type:'single' } })
        let windowObject = window.open(routerJump.href, '_blank')
        this.MessageInterval = setInterval(() => {
          if (windowObject) {
            windowObject.postMessage({
              sendPage: 'present',
              status: Cookies.get('token'),
              code: Cookies.get('tenant_code')
            }, '*')
          }
        }, 1000)
      }
      if (type === 'rotate') {
        this.$nextTick(() => {
          this.$refs['presentManagement'].dataForm.resourceId = this.pageId
          this.$refs['presentManagement'].visible = true
          this.$refs['presentManagement'].init()
        })
      }
    },
    addReportPop () {
      this.publishMessage('emitselectedgadgetPop', true)
    },
    handleExportPDF(){
      let data = this.downloadPdfList
      if (this._.find(this.downloadPdfList, (item) => { return (item.resourceId === this.pageId && !item.status) })) {
        this.$message.info('PDF now is exporting, please wait...')
        setTimeout(() => {
          this.$store.dispatch('setShowNotice', true)
        }, 1000)
        return false
      }
      let userData=`timezoneId=${this.$store.state.user.timezoneId}&timezoneOffset=${this.$store.state.user.timezoneOffset}&autotaskUrl=${this.$store.state.user.domainUrl.autotaskUrl}&huntressUrl=${this.$store.state.user.domainUrl.huntressUrl}&syncroMspUrl=${this.$store.state.user.domainUrl.syncroMspUrl}&cwUrl=${this.$store.state.user.domainUrl.cwUrl}&haloUrl=${this.$store.state.user.domainUrl.haloUrl}&timeFormat=${this.$store.state.user.timeFormat}&shareToken=${this.$store.state.user.shareToken}&comGridMaxNum=${this.comGridMaxNum}`
      for(let key in this.slicer){ 
        if(this.isShowExportPDF&&Array.isArray(this.slicer[key])&&this.slicer[key].length>1){
          return this.$message.error('Please select only one option in Slicer before exporting as PDF.')
        }       
        if(!key.endsWith('0')){          
          userData+= `&${key}=${encodeURIComponent(this.slicer[key])}`
        }
      }
      if(this.totalPages){
        userData+=`&totalPages=${this.totalPages}`
      }
      if (this.pdfLoading) return false;
      this.pdfLoading = true
      // this.$interface.login.exportDashboardPdf({
      //   url: `${window.location.origin}/publicReportPdf?pageid=${this.$route.query.pageid}&tenantCode=${this.$store.state.user.tenantCode}&format=${this.settingForm.size}&orientation=${this.settingForm.orientation}&${userData}`
      // }).then(res => {
      //   JsFileDownload(res.data, `${this.$route.query.name}.pdf`)
      // }).finally(() => {
      //   this.pdfLoading = false
      // })
      this.$interface.snapshots.leadingOut({
        userId: this.$store.state.user.id,
        resourceId: this.pageId,
        url: `${window.location.origin}/publicReportPdf?pageid=${this.$route.query.pageid}&tenantCode=${this.$store.state.user.tenantCode}&${userData}`
        // url: `https://appint.mspbots.ai/publicReportPdf?pageid=${this.pageId}&tenantCode=${this.$store.state.user.tenantCode}&${userData}`
      }).then(res => {
        if (res.data.code === 0) {
          this.$store.dispatch('setShowNotice', true)
        } else {
          this.$message.error(res.data.msg)
        }
      }).finally(() => {
        this.pdfLoading = false
      })
    }
  },
  destroyed () {
    window.removeEventListener('message', (event) => {
      if (event.data.message) {
        if (this.MessageInterval) {
          clearInterval(this.MessageInterval)
        }
      }
    })
  }
})
</script>
<style scoped lang='scss'>
::v-deep .el-menu{
  background: none;
}
::v-deep .el-menu.el-menu--horizontal {
  border-bottom: 0 !important;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.cardIcon {
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -1px;
}

.menu-item-header {
  height: 45px !important;
  line-height: 45px !important;
  margin: 0;
  font-size: 16px;
  color: #000;
  font-weight: 700;
}

.el-menu--horizontal > .el-menu-item {
  height: 45px !important;
  line-height: 45px !important;
}

.el-menu-item {
  height: 45px;
  line-height: 45px;
}

.e-list-item {
  height: 0px !important;
}

.filter-row {
  &-title {
    font-weight: bold;
  }
  &-content {
    border-bottom: 1px dashed #dfdfdf;
    padding: 0 10px 4px 10px;
    color: #999;
  }
}

.filter-list-title {
  color: #303133;
  font-size: 16px;
  line-height: 1;
  margin-bottom: 12px;
  padding: 0 5px;
  margin: 7px 0;
}

.filters-list {
  min-height: 120px;
  border: 1px solid #efefef;
  max-height: 250px;
  overflow-y: auto;
}

.filters-box ul,
.filter-list-box {
  list-style: none;
  padding: 0 5px;
  margin: 7px 0;
  word-break: break-word;
}

.filter-list-box li {
  height: 28px;
  line-height: 28px;
  margin-top: 5px;
}

.filters-box ul:last-child > li {
  border-bottom: none;
}
.view-name-icon {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
  .view-name {
    width: calc(100% - 35px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .view-icon {
    width: 35px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.icon-css-apply {
  cursor: pointer;
  color: #17b3a3;
}
.icon-css-delete {
  cursor: pointer;
  color: #f56c6c;
}
.cuifont {
  font-size: 14px;
  color: #404040;
  margin-right: 10px;
  padding: 7px;
  cursor: pointer;
  border-radius: 4px;
  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
}
.bot-css {
  // width: 235px;
  height: 45px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding-right: 10px;
}
</style>

<style lang="scss">
.menu-item-submenu {
  height: 45px !important;
  line-height: 45px !important;
  margin: 0;
}
.menu-item-submenu-item {
  height: 45px !important;
  line-height: 45px !important;
  margin: 0;
  .el-submenu__title {
    height: 45px !important;
    line-height: 45px !important;
    margin: 0;
  }
}
.app_menu .el-menu-item {
  // width: 200px !important;
}
.more_text_app {
  display: inline-block;
  // max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.more_text_app2 {
  display: inline-block;
  max-width: 500px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
